using UnityEngine;

namespace Whoot.DI.Context.Internal
{
    internal class GameObjectContextService : IGameObjectContextService
    {
        [Inject(Id = typeof(GameObjectContextService))]
        private IContextRepository _repository = default;

        [Inject] private GameObjectContextHelper _helper = default;

        public IContext GetGameObjectContextOrDefault(Component component, IContext defaultContext = null)
        {
            var id = _helper.GetInstanceId(component);

            if (_repository.HasContext(id)) return _repository.GetContext(id);
            var context = _helper.GetComponentInParentOnly<IContext>(component) ?? defaultContext;
            _repository.SetContext(id, context);
            return context;
        }
    }
}